使用OWIN Middleware Web API发送响应

时间:2017-01-27 20:02:37

标签: asp.net json asp.net-web-api2 owin owin-middleware


我试图在我的Web APi 2项目中自定义访问令牌json对象。 这是我成功完成的。但我无法弄清楚请求失败的情况。

这是我的自定义回复: -     { data: {}, success: 0, message: "failed" }

以下是GrantResourceOwnerCredentials中的ApplicationOAuthProvider方法,它继承了OAuthAuthorizationServerProvider

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
    ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    ApplicationUser user = userManager.Find(context.UserName, context.Password);
    bool reqFailed = false;
    string reqFailedMsg = "";

    if (user == null)
    {
        reqFailed = true;
        reqFailedMsg = "The user name or password is incorrect.";
    }

    if (!reqFailed && !user.EmailConfirmed)
    {
        reqFailed = true;
        reqFailedMsg = "The user email is not confirmed.";
        //context.SetError("invalid_grant", "The user email is not confirmed.");
        //return;
    }

    if (!reqFailed && !user.IsActive)
    {
        reqFailed = true;
        reqFailedMsg = "The user is disabled.";
        //context.SetError("invalid_grant", "The user is disabled.");
        //return;
    }

    if (reqFailed)
    {
        try
        {
            context.Response.Headers.Add(LMS.Utilities.Constants.MyMiddlewareHeader, new[] { (400).ToString() });
            context.Response.Headers.Add(LMS.Utilities.Constants.MyMiddlewareHeaderMsg, new[] { reqFailedMsg });
        }
        catch (Exception ex)
        {
        } 
        return;
    }

    var form = await context.Request.ReadFormAsync();

    if (form["deviceType"] != null && form["deviceToken"] != null)
    {
        user.DeviceToken = form["deviceToken"];
        user.DeviceType = form["deviceType"];

        userManager.Update(user);
    }

    ClaimsIdentity oAuthIdentity = userManager.GenerateUserIdentity(userManager, user,
        OAuthDefaults.AuthenticationType);
    ClaimsIdentity cookiesIdentity = userManager.GenerateUserIdentity(userManager, user,
        CookieAuthenticationDefaults.AuthenticationType);

    AuthenticationProperties properties = CreateProperties(user.UserName);
    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
    context.Validated(ticket);
    //context.Request.Context.Authentication.SignIn(cookiesIdentity);
    context.Request.Context.Authentication.SignIn(properties, cookiesIdentity);
    //return Task.FromResult<object>(null);
    }


中间件类: -

public class AuthenticationMiddleware : OwinMiddleware
{
    public AuthenticationMiddleware(OwinMiddleware next) : base(next) { 

    }

    public override async Task Invoke(IOwinContext context)
    {
        await Next.Invoke(context);
        if (context.Response.Headers.ContainsKey(Constants.MyMiddlewareHeader))
        {
            using (var reader = new StreamReader(context.Request.Body))
            {
                var headerValues = context.Response.Headers.GetValues(Constants.MyMiddlewareHeader);
                context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());
                context.Response.Headers.Remove(Constants.MyMiddlewareHeader);

                var headerValuesMessage = context.Response.Headers.GetValues(Constants.MyMiddlewareHeaderMsg);
                string msg = headerValuesMessage.FirstOrDefault().ToString();
                context.Response.Headers.Remove(Constants.MyMiddlewareHeaderMsg);

                string resp = Newtonsoft.Json.JsonConvert.SerializeObject(new ResponseViewModel<object>(new { }, (int)ResponseStatus.Fail, msg));

                var response = context.Response;
                var body = await reader.ReadToEndAsync();
                var bytes = Encoding.UTF8.GetBytes(resp);

                response.ContentLength = bytes.Length;
                await response.WriteAsync(bytes);

                return;
            }
        }
    }
}

我得到的是: -

{"error":"invalid_grant"}{"Data":{},"Status":0,"Message":"The user name or

你可以看到哪个是无效的json。

任何帮助将不胜感激。 谢谢!

0 个答案:

没有答案