I do have simple API controller, and I do need to return 401.
Method's return type is not IActionResult
so I can't just return Unauthorized()
How can I return Unauthorized in this case?
[Produces("application/json")]
public class MyController : Comntroller
{
public SomeData GetSomeData([FromBody]RequestData data)
{
if(!CheckAccessCondition(data, GetCurrentUser()))
// ?? how to return from here 401
///
}
}
Update:
IActionResult
is not a way. It is not type safe from one side, and would not allow to generate C# & Typescript clients for my API (now i'm using NSwag for this purpose)Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).
In order to return XML using an IActionResult method, you should also use the [Produces] attribute, which can be set to “application/xml” at the API Controller level. [Produces("application/xml")] [Route("api/[controller]")] [ApiController] public class LearningResourcesController : ControllerBase { ... }
You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages. Yes, your MVC code can be a consumer of a WebAPI, but not the other way around.
If the only reason you don't have a IActionResult return type is because you want to return json data, you can still return it and do this:
public IActionResult GetSomeData()
{
if (condition)
return Json(myData);
else
return Unauthorized();
}
A little hacky, but you can also simply return null and configure your response using HttpContext
public SomeData GetSomeData()
{
if (condition) return myData;
else
{
HttpContext.Response.StatusCode = 401;
return null;
}
}
If you need SomeData
for some reason such as type safety, one of your options are to set up a filter class.
public class MyAccessAttribute : Attribute, IActionFilter{
public void OnActionExecuting(ActionExecutingContext context)
{
if (condition)
context.Result = new UnauthorizedResult();
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
You can then use it on your action like this:
[MyAccess]
public SomeData GetSomeData(){
Update As of .netcore 2.1 you can now use generic ActionResult
public ActionResult<SomeData> GetSomeData(){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With