如何添加/更改.NET Web API的默认Json消息响应属性?

时间:2017-02-27 08:12:20

标签: c# .net asp.net-mvc

使用Web API中未经授权的调用示例,它将根据此提供响应。

image

  1. 有没有办法更改默认属性名称"消息"另一个名字,如" Reason" /" Description"对于不成功的API响应?

  2. 是否可以添加新的属性,例如"状态"?

2 个答案:

答案 0 :(得分:0)

是的只是使用如果您想从服务器更改Josn响应返回的结构,您可以使用asp.net mvc app中的以下代码创建新响应。

  // here you can use your own properties  which then can be send to client .
  return Json(new { Status= false ,Description = response.Message });

如果你有控制器方法,那么你应该返回JsonResult

如果您正在寻找通用解决方案,请查看本文可能会对您有所帮助。

http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information

答案 1 :(得分:0)

可以使用自定义AuthorizeAttribute完成。

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {

        public CustomAuthorizeAttribute ()
        {

        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            try
            {
                if (Authorize(actionContext))
                {
                    return;
                }
                HandleUnauthorizedRequest(actionContext);
            }
            catch (Exception)
            {
                //create custom response
                actionContext.Response = actionContext.Request.CreateResponse(
                    HttpStatusCode.OK,
                    customresponse
                );
                return;
            }

        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            //create custom unauthorized response

            actionContext.Response = actionContext.Request.CreateResponse(
                HttpStatusCode.OK,
                customunauthorizedresponse
            );
            return;
        }

        private bool Authorize(HttpActionContext actionContext)
        {
            //authorization logics
        }


    }

在您的api控制器方法中,您可以使用[CustomAuthorizeAttribute]

[Authorize]内容
相关问题