Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# URL上的MVC凭据_C#_Asp.net Mvc 4_Url - Fatal编程技术网

C# URL上的MVC凭据

C# URL上的MVC凭据,c#,asp.net-mvc-4,url,C#,Asp.net Mvc 4,Url,在控制器中使用MVC,我将如何传递凭据的值?不将凭据作为查询参数放置 // http://user1:pass1@localhost:80/GetData?Branch=1 public ActionResult GetPDF(int Branch) { // how will i get user1 as username, and pass1 as password? } 谢谢使用POST请求,以便可以通过请求头发送凭据在ajax请求头中提出一个POST请求,并在其中提及您的参数,

在控制器中使用MVC,我将如何传递凭据的值?不将凭据作为查询参数放置

// http://user1:pass1@localhost:80/GetData?Branch=1
public ActionResult GetPDF(int Branch) {
    // how will i get user1 as username, and pass1 as password?
}

谢谢

使用POST请求,以便可以通过请求头发送凭据

在ajax请求头中提出一个POST请求,并在其中提及您的参数,还可以进行编码/加密

大于jQuery 1.5,您可以$.ajaxsetup全局设置标题

然后将授权过滤器放入控制器中,以解密和分离凭据

如果您想通过控制器操作访问它,您可以这样做

var re = Request;
var headers = re.Headers;

if (headers.Contains("Username"))
{
    string token = headers.GetValues("Username").First();
}

通过这种方式,您可以授权和验证凭据,而无需传递数据或url字符串

var re = Request;
var headers = re.Headers;

if (headers.Contains("Username"))
{
    string token = headers.GetValues("Username").First();
}
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
// Gets header parameters
string authenticationString = actionContext.Request.Headers.Authorization.Parameter;

        string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));   

        // Gets username and password  
        string usrename = originalString.Split(':')[0];  
        string password = originalString.Split(':')[1];    
        // Validate username and password  
        if (!ApiSecurity.VaidateUser(usrename, password))  
        {   // returns unauthorized error  
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);  
        }  
    }    
    base.OnAuthorization(actionContext);  
}  }