小编Xar*_*uth的帖子

访问MVC 5中控制器中的Claim值

我在我的应用程序中使用了OWIN身份验证.

登录操作

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, result.UserFirstName));            
claims.Add(new Claim(ClaimTypes.Sid, result.UserID.ToString()));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
Run Code Online (Sandbox Code Playgroud)

我想从不同的操作访问UserName和UserID.如何访问声明中添加的值?

更新 我试过了

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, result.UserFirstName + " " + result.UserLastName));            
claims.Add(new Claim(ClaimTypes.Sid, result.UserIDNumber.ToString()));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var authenticationManager = Request.GetOwinContext().Authentication;
authenticationManager.SignIn(identity);

var claimsPrincipal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = claimsPrincipal;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我可以在快速窗口中查看值.但即使我无法访问该值.如何获得价值?

c# asp.net asp.net-mvc claims asp.net-mvc-5

47
推荐指数
2
解决办法
8万
查看次数

如何使用RestSharp发送请求

我试图使用RestSharp客户端POST请求,如下所示我将Auth Code传递给以下函数

public void ExchangeCodeForToken(string code)
{
    if (string.IsNullOrEmpty(code))
    {
        OnAuthenticationFailed();
    }
    else
    {           
        var request = new RestRequest(this.TokenEndPoint, Method.POST);
        request.AddParameter("code", code);
        request.AddParameter("client_id", this.ClientId);
        request.AddParameter("client_secret", this.Secret);
        request.AddParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
        request.AddParameter("grant_type", "authorization_code");
        request.AddHeader("content-type", "application/x-www-form-urlencoded");

        client.ExecuteAsync<AuthResult>(request, GetAccessToken);
    }
}

void GetAccessToken(IRestResponse<AuthResult> response)
{
    if (response == null || response.StatusCode != HttpStatusCode.OK
                         || response.Data == null 
                         || string.IsNullOrEmpty(response.Data.access_token))
    {
        OnAuthenticationFailed();
    }
    else
    {
        Debug.Assert(response.Data != null);
        AuthResult = response.Data;
        OnAuthenticated();
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到了响应.StatusCode = Bad Request.任何人都可以帮助我如何使用Restsharp客户端发布请求.

c# windows-phone-7 restsharp

31
推荐指数
4
解决办法
9万
查看次数

使用ClosedXML下载文件

所有

如何下载文件以便用户看到它正在下载(如使用流?)

我目前正在使用ClosedXML,但如果我使用SaveAs方法,我必须提供一个硬编码的URL,如果我只是给它文件名,它不会自动下载到下载文件夹.

下面的方法效果很好,但我必须创建自己的excel文件,该文件基于HTML,并且文件增长得太大,当我使用ClosedXML时,文件的大小只有50%或更少.代码如下:但是,下载行为是我希望它的样子.

有没有办法可以转换下面的代码,所以我可以把我的'工作簿'作为一个对象,它只是下载这个工作簿?

HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";    
HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
ctl.Page.EnableViewState =false;   
System.IO.StringWriter  tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
Run Code Online (Sandbox Code Playgroud)

谢谢

c# asp.net closedxml

24
推荐指数
3
解决办法
3万
查看次数

SaveChanges()上的验证错误

我的Asp.net mvc Web应用程序中有以下Action方法: -

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(SDJoin sdj, FormCollection formValues)
{
    Try
    {
        //code goes here
        repository.InsertOrUpdateSD(sdj.StorageDevice, User.Identity.Name, assetid);
        repository.Save();
    }
    catch (Exception ex)
    {
        //code goes here
    }
    PopulateViewBagData();
    return View(sdj);
}
Run Code Online (Sandbox Code Playgroud)

它调用以下方法: -

public void InsertOrUpdateSD(TMSStorageDevice sd, string username, long assetid)
{
    var resource = entities.Resources.AsNoTracking().SingleOrDefault(a => a.RESOURCEID == assetid);
    if (sd.TMSStorageDeviceID == default(int))
    {
        // New entity
        int technologyypeID = GetTechnologyTypeID("Storage Device");
        Technology technology = new Technology
        {
            IsDeleted = true,
            IsCompleted = false,
            TypeID …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc entity-framework

23
推荐指数
2
解决办法
7万
查看次数

让一个类将自己作为参数传递给泛型基类邪恶?

我第一次看到一位同事在实施对象池时这样做了.他将要作为参数汇集的类传递给泛型基类.这个基类列出了池代码.

奇怪的是基类会知道它的孩子.在每种正常情况下,这被认为是不好的做法.但在这种情况下,父母只是避免编写重复代码的技术解决方案.任何其他代码都不会引用基类.

这种结构的一个缺点是它"烧掉了基础类".您不能在层次结构的中间引入通用基类.此问题可能超出了主题范围.

以下是一个可以想象的例子:

public abstract class Singleton<T> where T : class
{
    public static T Instance { get; private set; }

    public Singleton()
    {
        if (Instance != null)
            throw new Exception("Singleton instance already created.");
        Instance = (T) (object) this;
    }
}

public class MyClass : Singleton<MyClass>
{
}
Run Code Online (Sandbox Code Playgroud)

改进代码:

public abstract class Singleton<T> where T : Singleton<T>
{
    public static T Instance { get; private set; }

    public Singleton()
    {
        if (Instance != null)
            throw new Exception("Singleton instance already …
Run Code Online (Sandbox Code Playgroud)

c# oop generics design-patterns

16
推荐指数
1
解决办法
2390
查看次数

Image.FromStream()方法返回Invalid Argument异常

我从智能相机成像器捕获图像并通过套接字编程从相机接收字节数组(.NET应用程序是客户端,相机是服务器).

问题是我在运行时得到System.InvalidArgument异常.

private Image byteArrayToImage(byte[] byteArray) 
{
    if(byteArray != null) 
    {
        MemoryStream ms = new MemoryStream(byteArray);
        return Image.FromStream(ms, false, false); 
        /*last argument is supposed to turn Image data validation off*/
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

我在很多论坛上都搜索过这个问题并尝试过许多专家给出的建议,但没有任何帮助.

我不认为字节数组有任何问题,因为当我将相同的字节数组输入我的VC++ MFC客户端应用程序时,我得到了图像.但这在C#.NET中不起作用.

谁能帮我 ?

PS:

我试图完成同样任务的其他方法是:

1.

private Image byteArrayToImage(byte[] byteArray)
{
    if(byteArray != null) 
    {
        MemoryStream ms = new MemoryStream();
        ms.Write(byteArray, 0, byteArray.Length);
        ms.Position = 0; 
        return Image.FromStream(ms, false, false);
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

2.

private Image byteArrayToImage(byte[] byteArray) 
{
    if(byteArray != null) 
    { …
Run Code Online (Sandbox Code Playgroud)

.net c# memorystream image exception

11
推荐指数
2
解决办法
4万
查看次数

为什么viewbag值没有传回视图?

直截了当的问题,似乎无法让我的viewBag值显示在完成表单后用户指向的视图中.

请指教..谢谢

我的索引ActionResult简单返回模型数据..

public ActionResult Index()
{
    var source = _repository.GetByUserID(_applicationUser.ID);
    var model = new RefModel
    {
        test1 = source.test1,
    };
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

我的编辑"ActionResult,只使用与索引相同的模型数据.

我的帖子"编辑"ActionResult,将新值分配给模型并重定向到索引页面,但索引页面不显示ViewBag值?

[HttpPost]
public ActionResult Edit(RefModell model)
{
    if (ModelState.IsValid)
    {
        var source = _repository.GetByUserID(_applicationUser.ID);
        if (source == null) return View(model);

        source.test1 = model.test1;
        _uow.SaveChanges();

        @ViewBag.Message = "Profile Updated Successfully";
        return RedirectToAction("Index");      
    }
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

在我的索引视图中......

@if(@ViewBag.Message != null)
{
    <div>
        <button type="button">@ViewBag.Message</button>
    </div>
}
Run Code Online (Sandbox Code Playgroud)

c# html5 asp.net-mvc-4

9
推荐指数
1
解决办法
3万
查看次数

使用INotifyPropertyChanged的代码片段

我找到了INotifyPropertyChanged的这段代码片段

但是它显示了这样的代码:

INotifyPropertyChanged的

我会这样的:

  1. 对于公众:第一个字母的大写字母+ ...

  2. 私人:第一个字母+下划线+小写字母+ ...

我怎样才能做到这一点?

编辑:无需键入公共字段和私有字段

<Snippet>
    <Declarations>
        <Literal>
            <ID>type</ID>
            <ToolTip>Property type</ToolTip>
            <Default>string</Default>
        </Literal>
        <Literal>
            <ID>property</ID>
            <ToolTip>Property name</ToolTip>
            <Default>MyProperty</Default>
        </Literal>
        <Literal>
            <ID>notifyMethod</ID>
            <ToolTip>name of method to raise PropertyChanged event</ToolTip>
            <Default>NotifyPropertyChanged</Default>
        </Literal>
    </Declarations>
    <Code Language="csharp">
        <![CDATA[private $type$ _$property$;
            public $type$ $property$
            {
                get { return _$property$;}
                set 
                { 
                    if (value != _$property$)
                    {
                        _$property$ = value;
                        $notifyMethod$("$property$");
                    }
                }
            }
        $end$]]>
    </Code>
</Snippet>
Run Code Online (Sandbox Code Playgroud)

c# inotifypropertychanged visual-studio code-snippets

8
推荐指数
2
解决办法
9434
查看次数

将ASP.Net GridView从一个页面传递到另一个页面

我想将所有gridview值传递到另一个页面,我在PatientDetails.aspx页面中有一个gridview,下面是一个按钮

<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" 
    AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateSelectButton="true"
    AutoGenerateDeleteButton="true" OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />
                <asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
                <asp:Button ID="btnSelect" runat="server" Text="Select" CommandName = "Select" />
            </ItemTemplate>
        </asp:TemplateField>

        <asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
        <asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
        <asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />                                
        <asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>" 
    SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" OnCommand="btnformatric_Command" /> …
Run Code Online (Sandbox Code Playgroud)

c# asp.net gridview

7
推荐指数
1
解决办法
2万
查看次数

编码UTF8 C#进程

我有一个处理vbscript并生成输出的应用程序.

private static string processVB(string command, string arguments)
{
    Process Proc = new Process();
    Proc.StartInfo.UseShellExecute = false;
    Proc.StartInfo.RedirectStandardOutput = true;
    Proc.StartInfo.RedirectStandardError = true;
    Proc.StartInfo.RedirectStandardInput = true;
    Proc.StartInfo.StandardOutputEncoding = Encoding.UTF8;
    Proc.StartInfo.StandardErrorEncoding = Encoding.UTF8;
    Proc.StartInfo.FileName = command;
    Proc.StartInfo.Arguments = arguments;
    Proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //prevent console      window from popping up
    Proc.Start();
    string output = Proc.StandardOutput.ReadToEnd();
    string error = Proc.StandardError.ReadToEnd();

    if (String.IsNullOrEmpty(output) && !String.IsNullOrEmpty(error))
    {
        output = error;
    }
    //Console.Write(ping_output);

    Proc.WaitForExit();
    Proc.Close();

    return output;
}
Run Code Online (Sandbox Code Playgroud)

我想我已经设置了与编码属性相关的所有内容.processVB方法将获取命令作为VBscript文件及其参数.

C#方法processVB正在处理现在生成输出的VBScript文件,如下所示.

"?"

但我应该得到原文

"äåéö€"

我已正确设置编码.但我无法做到正确.

我究竟做错了什么?

c# encoding process utf-8

6
推荐指数
1
解决办法
6069
查看次数