Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
57 views
in Technique[技术] by (71.8m points)

c# - Overwrite request object in ASP .NET Core

I have base class for every request in my app:

public abstract class BaseDto
{
   public string Uid { get; set; }
}

public class RequestDto : BaseDto
{
    public string SomeData { get; set; }
}

Im using my ReuqestDto class in my controller actions:

[HttpGet]
public IEnumerable<string> Get(RequestDto req)
{
    // some logic on request
    if (req.Uid != null)
    {
        // perform action
    }

}

The user passing only SomeData property to me. In my JWT Token i have saved some information about Uid for BaseDto. What is the best way to write data to Uid using middleware/filter to have that information in my Get() method? I Tried to serialized HttpContext.Request.Body but not success because i cant find, how to do it properly. Or maybe there are better solutions for this problem? How to write data to my incoming objects in app?

question from:https://stackoverflow.com/questions/65836643/overwrite-request-object-in-asp-net-core

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is probably what you want.

You should to create own interface for models like that

public interface IMyRequestType { }

Your model should implement it for finding model in FilterAttribute

public class MyModel : IMyRequestType
{
    public string ID { get; set; }
}

And create your filter attribute with OnActionExecuting implentation

public class MyFilterAttribute : TypeFilterAttribute
{
    public MyFilterAttribute() : base(typeof(MyFilterImpl)) { }

    private class MyFilterImpl : IActionFilter
    {
        private readonly ILogger _logger;

        public MyFilterAttributeImpl(ILoggerFactory loggerFactory)
        {
            // get something from DI
            _logger = loggerFactory.CreateLogger<MyFilterAttributeImpl>();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            // get your request model
            var model = context.ActionArguments.Values.OfType<IMyRequestType>().Single();

            // get your key
            //context.HttpContext.User or whatever

            // do something with model
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // perform some logic work
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...