如何在MVC 6中创建响应

时间:2016-03-26 20:40:59

标签: asp.net-mvc asp.net-mvc-4 asp.net-core-mvc

我在MVC 4中有这个代码:

private HttpResponseMessage GetAuthToken(Guid userId)
        {
            var token = _tokenService.GenerateToken(userId);
            var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized");
            response.Headers.Add("Token", token.AuthToken);
            response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
            response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");

            return response;
        }

如何将此代码迁移到MVC 6?

1 个答案:

答案 0 :(得分:2)

这适用于MVC 6.

public ObjectResult GetAuthToken(Guid userId)
{
  var token = _tokenService.GenerateToken(userId);
  var r = new HttpOkObjectResult(token);

  Response.Headers.Add("Token", token.AuthToken);
  Response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
  Response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");

  return r;
}

或者只是Ok方法

public ObjectResult GetAuthToken(Guid userId)
{
  var token = _tokenService.GenerateToken(userId);
  Response.Headers.Add("Token", token.AuthToken);
  Response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
  Response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");

  return Ok(token);
}

Here是从Web Api 2 MVC 6转换的样本列表。